import numpy as np
import pandas as pd
from pyecharts.charts import Line, Bar, Pie, Radar, WordCloud, Page
from pyecharts.components import Table
from pyecharts import options as opts
from pyecharts.globals import ThemeType
from bs4 import BeautifulSoup
from time import sleep

# 设置全局主题
theme_config = ThemeType.CHALK
v_title = '可视化大屏展示'
# 表格和标题的颜色
table_color = ""
if theme_config == ThemeType.DARK:
    table_color = '#333333'
elif theme_config == ThemeType.CHALK:
    table_color = '#293441'
elif theme_config == ThemeType.PURPLE_PASSION:
    table_color = '#5B5C6E'
elif theme_config == ThemeType.ROMANTIC:
    table_color = '#F0E8CD'
elif theme_config == ThemeType.ESSOS:
    table_color = '#FDFCF5'
else:
    table_color = ''


# 饼状图
# def get_pie():
#     data = pd.read_excel('./flask_test/xlsx_data/list_type.xlsx')
#     data = data.head(10)
#     data = data[['类型', '类型数量']].values.tolist()
# pie = Pie(init_opts=opts.InitOpts(width="450px", height="350px", theme=theme_config, chart_id='pie'))
# pie.add(series_name='类型数量', data_pair=data)
# pie.set_global_opts(
#     # title_opts=opts.TitleOpts(title="哔哩哔哩热门视频各类型信息"),
#     legend_opts=opts.LegendOpts(
#         pos_left="left",
#         pos_top="middle",
#         orient="vertial"
#     )
# )
# # pie.render('./templates/pie.html')
# return pie


def get_lean_people():
    df = pd.read_csv("data/learn_people.csv")
    df.columns = ['时间', '在线人数']
    # df = df.drop_duplicates('点赞')
    # 准备数据
    x_data = df['时间']
    y_data = df['在线人数']

    # 生成折线图
    line = Line(init_opts=opts.InitOpts(width="800px", height="350px", chart_id='line'))
    # 插入x轴和y轴
    line.add_xaxis(x_data)
    line.add_yaxis(
        series_name='在线人数',
        y_axis=y_data)

    # 设置全局配置项
    line.set_global_opts(
        xaxis_opts=opts.AxisOpts(name='时间', type_='category'))
    line.set_global_opts(
        # title_opts=opts.TitleOpts(title='在线人数'),
        yaxis_opts=opts.AxisOpts(name='在线人数', type_='value'))
    # 设置系列配置项
    line.set_series_opts(
        label_opts=opts.LabelOpts(is_show=False))
    # 渲染到notebook、
    line.render('line.html')
    # return line
#
#
def get_pie2(num):
    df = pd.read_csv('./flask_test/xlsx_data/ALLbilibili.csv')
    df = df.sort_values('播放量', ascending=False).reset_index()
    df = df[['UP主', '播放量', '弹幕', '点赞', '投币', '收藏', '转发']]
    data = df[['UP主', '播放量']].values.tolist()
    # print(len(data))
    num_index = 15  # 分隔的数量
    # num = int(len(data) / num_index)
    # print(type(data))
    # print("---"*30)
    # print(type(data[0:20]))
    # for i in range(0, num):
    #     end += num_index
    #     pie_data = data[strat:end]
    #     print(pie_data, "\n")
    #     strat += num_index
    start = num * num_index
    end = num * num_index + num_index
    data_list = data[start:end]
    # print(data_list)
    pie2 = Pie(init_opts=opts.InitOpts(width="800px", height="400px", theme=theme_config, chart_id='pie2'))
    pie2.add(series_name='播放量', data_pair=data_list)
    pie2.set_global_opts(
        title_opts=opts.TitleOpts(title="哔哩哔哩热门视频UP主信息"),
        legend_opts=opts.LegendOpts(
            pos_left="left",
            pos_top="middle",
            orient="vertial"
        )
    )
    pie2.render('pie2.html')
    print('生成完毕:饼图')
    return pie2


#
#
# # 折线图
# def get_line():
#     df = pd.read_csv("./flask_test/xlsx_data/ALLbilibili.csv")
#     df2 = df[['点赞', '投币']].sort_values('点赞').reset_index()
#     df2 = df2[int(len(df2) * 1 / 3):int(len(df2) * 2 / 3)]
#     df2 = df2.drop_duplicates('点赞')
#     # 准备数据
#     x_data = df2['点赞']
#     y_data = df2['投币']
#
#     # 生成折线图
#     line = Line(init_opts=opts.InitOpts(width="450px", height="350px", theme=theme_config, chart_id='line'))
#     # 插入x轴和y轴
#     line.add_xaxis(x_data)
#     line.add_yaxis(
#         series_name='投币',
#         y_axis=y_data)
#
#     # 设置全局配置项
#     line.set_global_opts(
#         xaxis_opts=opts.AxisOpts(name='点赞', type_='category'))
#     line.set_global_opts(
#         # title_opts=opts.TitleOpts(title='投币与点赞对比'),
#         yaxis_opts=opts.AxisOpts(name='投币', type_='value'))
#     # 设置系列配置项
#     line.set_series_opts(
#         label_opts=opts.LabelOpts(is_show=False))
#     # 渲染到notebook、
#     # line.render('./templates/line.html')
#     print('生成完毕:折线图')
#     return line
#
#
# def tab0(name, color):  # 标题
#     c = (Pie(init_opts=opts.InitOpts(chart_id='title1')).
#     set_global_opts(
#         title_opts=opts.TitleOpts(title=name, pos_left='center', pos_top='center',
#                                   title_textstyle_opts=opts.TextStyleOpts(color=color, font_size=20))))
#     return c
#
#
# def tab_big():
#     table = Table()
#     table.add(headers=[v_title], rows=[], attributes={
#         "align": "center",
#         "border": False,
#         "padding": "2px",
#         "style": "background:{}; width:1350px; height:50px; font-size:25px; color:#C0C0C0;".format(table_color)
#     })
#     table.render('大标题.html')
#     print('生成完毕:大标题')
#
#
# def tab1(name, color):  # 标题
#     c = (Pie(init_opts=opts.InitOpts(chart_id='title2')).
#     set_global_opts(
#         title_opts=opts.TitleOpts(title=name, pos_left='center', pos_top='center',
#                                   title_textstyle_opts=opts.TextStyleOpts(color=color, font_size=25))))
#     return c
#
#
# 柱状图
def get_bar():
    df_bar = pd.read_excel('./flask_test/xlsx_data/first_list_type_data.xlsx')
    df_bar = df_bar.sort_values('播放量', ascending=False).reset_index()
    df = df_bar[['标签', '播放量', '评论', '点赞', '投币', '收藏', '转发']]
    x_data = list(df['标签'])
    y_data = list(df['播放量'])
    y_data1 = list(df['评论'])
    y_data2 = list(df['点赞'])
    y_data3 = list(df['投币'])
    y_data4 = list(df['收藏'])
    y_data5 = list(df['转发'])
    bar = Bar(init_opts=opts.InitOpts(width="800px", height="350px", theme=theme_config, chart_id='bar'))
    bar.add_xaxis(x_data)
    bar.add_yaxis(series_name='播放量', y_axis=y_data)
    bar.add_yaxis(series_name='评论', y_axis=y_data1)
    bar.add_yaxis(series_name='点赞', y_axis=y_data2)
    bar.add_yaxis(series_name='投币', y_axis=y_data3)
    bar.add_yaxis(series_name='收藏', y_axis=y_data4)
    bar.add_yaxis(series_name='转发', y_axis=y_data5)
    bar.set_global_opts(
        # title_opts=opts.TitleOpts(title='各类标签对比'),
        xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(rotate=30)))
    bar.render('bar.html')
    print('生成完毕:柱形图')
#     return bar
#
#
# def get_WordCloud():
#     data = pd.read_excel("./flask_test/xlsx_data/list_type.xlsx")
#     data_radar = []
#     for row in range(data.shape[0]):
#         for col in range(1, data.shape[1]):
#             value = str(data.iloc[row, col])
#         data_radar.append((data["类型"][row], value))
#
#     wordCloud = WordCloud(init_opts=opts.InitOpts(width="450px", height="350px", theme=theme_config, chart_id='wcl'))
#
#     wordCloud.add(series_name="热点分析", data_pair=data_radar, word_size_range=[6, 66])
#     wordCloud.set_global_opts(
#         title_opts=opts.TitleOpts(
#             # title="热点分析",
#             title_textstyle_opts=opts.TextStyleOpts(font_size=23)
#         ),
#         tooltip_opts=opts.TooltipOpts(is_show=True),
#     )
#     # wordCloud.render("./templates/basic_wordcloud.html")
#     print('生成完毕:词云图')
#     return wordCloud
#
#
# def get_radar():
#     data = pd.read_excel("./flask_test/xlsx_data/first_list_type_data.xlsx")
#
#     data_name = []
#     data_radar = []
#     data_color = ['#CD0000', '#00BFFF', '#7B68EE', '#F4A460', '#00FFFF', '#00FA9A',
#                   '#ADFF2F', '#FFC0CB', '#FF0000', '#FFF0F5', '#00FF00', '#FFFF00',
#                   '#20B2AA', '#00FFFF', '#7FFFD4', '#B0C4DE', '#1E90FF', '#FFF8DC',
#                   '#FFE4E1', '#E0FFFF']
#     for row in range(data.shape[0]):
#         value = []
#         for col in range(1, data.shape[1]):
#             value.append(int(data.iloc[row, col]))
#         data_radar.append(value)
#         data_name.append(data["标签"][row])
#     scope = []
#     for col in range(1, data.shape[1]):
#         scope.append(max(data.iloc[:, col]))
#
#     radar = Radar(init_opts=opts.InitOpts(width="450px", height="350px", theme=theme_config, chart_id='radar'))
#     radar.add_schema(
#         schema=[
#             opts.RadarIndicatorItem(name="播放量（Play volume）", max_=scope[0]),
#             opts.RadarIndicatorItem(name="评论数（Number of comments）", max_=scope[1]),
#             opts.RadarIndicatorItem(name="点赞数（Give the thumbs-up）", max_=scope[2]),
#             opts.RadarIndicatorItem(name="投币（Coin-operated）", max_=scope[3]),
#             opts.RadarIndicatorItem(name="收藏（Collection）", max_=scope[4]),
#             opts.RadarIndicatorItem(name="转发（Forward）", max_=scope[5]),
#         ],
#         splitarea_opt=opts.SplitAreaOpts(
#             is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1)
#         ),
#         textstyle_opts=opts.TextStyleOpts(color="#fff"),
#     )
#
#     for i, v2 in enumerate(data_radar, 0):
#         radar.add(
#             series_name=data_name[i],
#             data=[v2],
#             linestyle_opts=opts.LineStyleOpts(color=data_color[i]),
#         )
#     radar.set_series_opts(label_opts=opts.LabelOpts(is_show=False))
#     radar.set_global_opts(
#         # title_opts=opts.TitleOpts(title="对比标签数据")
#     )
#     # radar.render("./templates/basic_radar_chart.html")
#     print('生成完毕:雷达图')
#     return radar
#
#
def all_page():
    page = Page(
        page_title="基于python的热门数据分析大屏",
        layout=Page.DraggablePageLayout,  # 拖拽方法
    )
    for i in range(10):
        page.add(
            # tab0("OFFICETOUCH", "#2CB34A"),
            # get_radar(),
            # tab1("数据可视化大屏", "#2CB34A"),
            # get_WordCloud(),
            get_bar(),
            # get_line(),
            get_pie2(i),
            # get_pie(),
        )
        # page.render("临时大屏.html")
        Page.save_resize_html(
            source="临时大屏.html",
            cfg_file="chart_config.json",
            dest="大屏_最终_0426.html"
        )
        print("生成成功")
        sleep(10)


if __name__ == '__main__':
    # get_radar()
    # get_WordCloud()
    # get_bar()
    # get_line()
    # get_pie2(1)
    # get_pie()
    all_page()
    # get_lean_people()